<?php
	/**
	* Products Get list - For filter, called by ajax
	* return in Json format
	* @author trungdt
	* @since Oct 5, 2011
	* 
	* Change logs
	* Oct 25, 2011 - trungdt - add param action_mode
	*                          action_mode = 1: search
	*                          action_mode = 2: new product
	*                          action_mode = 3: hot product
	*                          action_mode = 4: on sale
	*                          action_mode = 5: hot product
	*                          action_mode is empty: default search for products list show
	*/
	if (!defined('EXPONENT')) exit('');

	/**
	* This function make beatiful search term
	* 
	* @param mixed $search
	* @return string
	*/
	function _prettySearch($search){
		$temp_search=array();
		while (0<1)
		{
			$search_pos=strpos($search,"[");
			//echo "pos 1 = " .$search_pos;
			if ($search_pos===false) break;
			$search_pos2=strpos($search,"]");
			//echo "pos 2 = ".$search_pos2;
			if ($search_pos2===false) break;

			$s=substr($search,$search_pos+1,$search_pos2-$search_pos-1);
			$temp_search[]=$s;
			$search=substr($search,0,$search_pos).substr($search,$search_pos2+1);
		}
		if (count($temp_search) == 0)
			$temp_search[]=$search;
		return $temp_search;
	}

	/**
	* This function return true if $_REQUEST[param_id] not null, not empty
	* @author trungdt
	* @since Oct 12, 2011
	*/
	function _check_null($param_id){
		if (isset($_REQUEST[$param_id]) && _ab_safe_html_string(trim($_REQUEST[$param_id])) != '')
			return true;
		else
			return false;
	}

	$sql_where=" AND (public_state = 1) ";

	$pager_param_array=array();

	if (_check_null("action_mode"))
	{
		$action_mode = intval($_REQUEST['action_mode']);
		if ($action_mode == 1) // search mode 
		{
			$search_string="";
			if (_check_null("search_string"))
				$search_string = _ab_safe_html_string(strip_tags($_REQUEST['search_string']));
			$search_string =   @array_map("addslashes",_prettySearch($search_string));
			foreach ($search_string as $v)
			{
				if ((strlen($v)>1) && (substr($v,0,1) == "@")) // perform a search SKU
				{
					$v=substr($v,1);
					$sql_where.=" AND (sku = '{$v}')";
				}
				else
				// Nov 24, 2011 - trungdt - customer want to add field sku 
				$sql_where.=" AND ((title REGEXP '{$v}') OR (search_spec REGEXP '{$v}') OR (search_description REGEXP '{$v}') OR (search_des REGEXP '{$v}') OR (sku  REGEXP '{$v}'))";
			}
		}
		else
		if ($action_mode == 2){ // new product
			
		}
		else 
		if ($action_mode == 3){
			$sql_where.=" AND (hot_product = 1)";
		}
		else
		if ($action_mode == 4)
		{
			$sql_where.=" AND (on_sale = 1)";
		}
		else if ($action_mode == 5)
		{
			$sql_where.=" AND (best_seller = 1)";
		}
		else if ($action_mode == 6)
		{
			// by brand
		}
	}
	// build sql where for normal way
	if (_check_null("cat_seo_name"))
	{
		$pager_param_array['name']=_ab_safe_html_string($_REQUEST['cat_seo_name']);
		$cat=productsmodule::__GetCategoryBySeoName($pager_param_array['name']);
		$temp="";
		if ($cat)
			$sql_where.=" AND (".productsmodule::__CategoriesBuildConditionRecursive($temp,$cat->id).")";
	}

	if (_check_null("brand_id"))
	{
		$pager_param_array['brand_id']=$_REQUEST['brand_id'];
		$brand_filter=explode(";",_ab_safe_html_string($_REQUEST['brand_id']));
		$sql="";
		foreach ($brand_filter as $v)
		{
			$v=trim($v); $vi=intval($v);
			if ($v !='' && $vi > 0)
			{
				if ($sql!= '')
					$sql.=" OR ";
				$sql.="  (brand_id = ". $vi.")";
			}
		}
		if ($sql!= "")
			$sql_where.=" AND ({$sql})";
	}

	// price filter
	if (_check_null("price_list"))
	{
		$pager_param_array['price_list']=$_REQUEST['price_list'];
		$price_list=explode(";",_ab_safe_html_string($_REQUEST['price_list']));
		$sql="";
		foreach ($price_list as $v)
		{
			$temp = explode(":", $v);
			if (count($temp)<2)
				continue;
			$first_price = intval(array_shift($temp));
			$second_price = intval(array_shift($temp));
			if ($sql!= '')
				$sql.=" OR ";
			if  ($second_price > -1)
			{
				if ($first_price == 0)
					$sql.=" (price <= {$second_price})";
				else
					$sql.=" ((price >= {$first_price}) AND (price <= {$second_price}))";
			}
			else
				$sql.=" (price >= {$first_price})";
		}
		if ($sql!= "")
			$sql_where.=" AND ({$sql})";
	}

	// rating
	if (_check_null("stars"))
	{
		$pager_param_array['stars']=$_REQUEST['stars'];
		$rating=intval($_REQUEST['stars']);
		if ($rating == 5)
			$sql_where.=" AND (stars={$rating})";
		else
			$sql_where.=" AND (stars >= {$rating})";
	}

	//product state
	if (_check_null("product_state"))
	{
		$pager_param_array['product_state']=$_REQUEST['product_state'];
		$product_state=explode(";",_ab_safe_html_string($_REQUEST['product_state']));

		$sql="";
		foreach ($product_state as $v)
		{
			$v=trim($v); $vi=intval($v);
			if ($v !='' && $vi >= 0)
			{
				if ($sql!= '')
					$sql.=" OR ";
				$sql.="  (product_state = ". $vi.")";
			}
		}
		if ($sql!='')
			$sql_where.=" AND ({$sql})";
	}

	//product state2
	if (_check_null("product_state2"))
	{
		$pager_param_array['product_state2']=$_REQUEST['product_state2'];
		$product_state2=explode(";",_ab_safe_html_string($_REQUEST['product_state2']));

		$sql="";
		foreach ($product_state2 as $v)
		{
			$v=trim($v); $vi=intval($v);
			if ($v !='' && $vi >= 0)
			{
				if ($sql!= '')
					$sql.=" OR ";
				$sql.="  (product_state2 = ". $vi.")";
			}
		}
		if ($sql!='')
			$sql_where.=" AND ({$sql})";
	}

	// sort by
	$sql_sort="";
	if (_check_null("sort_by"))
	{
		$pager_param_array['sort_by']=$_REQUEST['sort_by'];
		$s=intval($_REQUEST['sort_by']);
		switch ($s)
		{
			case 0:
				$sql_sort=" ORDER BY best_seller DESC ";
				break;
			case 1: 
				$sql_sort=" ORDER BY on_sale DESC ";
				break;
			case 2: 
				$sql_sort=" ORDER BY hot_product DESC, best_seller DESC, stars DESC ";
				break;
			case 3: 
				$sql_sort=" ORDER BY stars DESC ";
				break;
			case 4: 
				$sql_sort=" ORDER BY price ASC ";
				break;
			case 5: 
				$sql_sort=" ORDER BY price DESC";
				break;
			default:  // default the same with 6: new product show first
				$sql_sort=" ORDER BY post_date DESC";
				break;
		}
	}

	$count=$db->countObjects("productsmodule_products", "location_data = '".serialize($loc)."' {$sql_where}");

	// pagination
	$page=1;
	if (isset($_REQUEST['page']))
		$page=intval($_REQUEST['page']);
	$pageSize=20;
	if (isset($_REQUEST['pageItems']))
		$pageSize=intval($_REQUEST['pageItems']);
	$start=($page-1)*$pageSize;

	// calculation how many pages
	$pages=ceil($count/$pageSize);

	if (isset($_REQUEST['page']))
		$pager_param_array['page']=$_REQUEST['page'];
	if (isset($_REQUEST['pageItems']))
		$pager_param_array['pageItems']=$_REQUEST['pageItems'];

	// get module configure
	$config=$db->selectObject("productsmodule_config", "location_data = '".serialize($loc)."'");

	$products=$db->selectObjects("productsmodule_products", "location_data = '".serialize($loc)."' {$sql_where} {$sql_sort} LIMIT {$start}, {$pageSize}");
	$price_max=0; $price_min=0;
	$products=productsmodule::__ProductProcess($products,$config, $price_max, $price_min, false);

	// fetch to template
	$template=new template("productsmodule","_ProductListRender",$loc);
	$template->register_permissions(array('administrate',"configure", "create", "edit", "delete"),$loc);
	$template->assign("products", $products);
	$template->assign("product_count", count($products));

	// for pagination
	$template->assign("pager_params", $pager_param_array);
	$template->assign("page", $page);
	$template->assign("pages", $pages);
	// end pagination
	$template->output();
?>